package ServerStuff;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.sql.Date;
import java.util.Calendar;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.JSONException;
import org.json.JSONObject;

import Database.DatabaseConnector;

@WebServlet("/SubmitPayrollServlet")
public class SubmitPayrollServlet extends HttpServlet
{
	private static final long serialVersionUID = 1L;
	
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
	{
		DatabaseConnector db = new DatabaseConnector();
		try {
			long employee = Long.parseLong(request.getParameter("employeeid"));
			
			String[] start = request.getParameter("start").split("-");
			String[] finished = request.getParameter("end").split("-");
			
			
			Calendar calendar = Calendar.getInstance();
			calendar.set(Integer.parseInt(start[0]), Integer.parseInt(start[1])-1, Integer.parseInt(start[2]));
			Date startDate = new Date(calendar.getTimeInMillis());
			calendar.set(Integer.parseInt(finished[0]), Integer.parseInt(finished[1])-1, Integer.parseInt(finished[2]));
			Date finishedDate = new Date(calendar.getTimeInMillis());
			
			boolean updated = db.markTimeSheetsPayed(employee, startDate, finishedDate);
			JSONObject result = new JSONObject();
			result.put("updated", updated);
			
			response.getWriter().print(result);
			response.setStatus(HttpURLConnection.HTTP_ACCEPTED);
		}
		catch (JSONException e) {
			e.printStackTrace();
			response.setStatus(HttpURLConnection.HTTP_BAD_REQUEST);
		}
		
		catch (IOException e) {
			e.printStackTrace();
			response.setStatus(HttpURLConnection.HTTP_BAD_REQUEST);
		}
		
		catch(NullPointerException e) {
			e.printStackTrace();
			response.setStatus(HttpURLConnection.HTTP_BAD_REQUEST);
		}
	}
}
